import math
import random

from webapp.extensions import AppException
from webapp.models import CourseTable, Session, Plan, db, ScheduleTable, Grade


class CourseScheduleService:
    @staticmethod
    def getRandom():
        randomNum = random.randint(0, 7)
        while randomNum % 2 != 0:
            randomNum = random.randint(0, 7)
        return randomNum

    @staticmethod
    def arrangeSchedule(id):
        # 准备一些必要信息
        coursetable = CourseTable.query.filter(CourseTable.id == id).one_or_none()
        if coursetable is None:
            raise AppException("没有查到该课程的信息")
        sessionId = coursetable.sessionId
        # 获取课程所属学期的周数
        session = db.session.query(Session).filter(Session.id == sessionId).one_or_none()
        # 获取课程所属教学计划的计划节数
        plan = Plan.query.filter(Plan.id == coursetable.plan).one_or_none()
        # 查询该课程所管理的班级的可排课周次
        grade = Grade.query.filter(Grade.classid == coursetable.teachclass).first()
        if coursetable is None:
            raise AppException("该课程未绑定到系统中的班级")
        # 数据库中存入的数据为1,2,3 需要分割下
        if "" == grade.studyweek or None == grade.studyweek:
            raise AppException("该课程绑定班级未设置可排课周次")
        studyweekstr = grade.studyweek.split(",")
        # 查询当前学期的课程安排情况,用于判断排课是否冲突
        # 计算平均每周的上课数
        # 计划节数/该课程在本学期的上课周数
        avgWeekSection = 0
        if coursetable.startW - coursetable.endW != 0:
            avgWeekSection = plan.timerange / (coursetable.endW - coursetable.startW)
            avgWeekSection = math.ceil(avgWeekSection)
        else:
            avgWeekSection = plan.timerange
        timerange = plan.timerange
        scheduletables = []
        coursetable.status = 2
        db.session.commit()
        ScheduleTable.query.filter(ScheduleTable.courseId == id).delete()
        # 从开始周和结束周之间开始循环
        for weekrange in range(coursetable.startW, coursetable.endW):
            # 每周循环开始前，初始化一个数组，该数组纪录了，本周的排课情况
            tempavg = avgWeekSection
            arrangeArray = [[0 for i in range(8)] for j in range(5)]
            if str(weekrange) not in studyweekstr:
                print(weekrange)
                continue
            if timerange > 0:
                while tempavg > 0:
                    randomDay = random.randint(0, 4)
                    randomSection = CourseScheduleService.getRandom()
                    if arrangeArray[randomDay][randomSection] == 1:
                        randomDay = random.randint(0, 4)
                        randomSection = CourseScheduleService.getRandom()
                    arrangeArray[randomDay][randomSection] = 1
                    arrangeArray[randomDay][randomSection + 1] = 1
                    scheduletable = ScheduleTable(
                        courseId=coursetable.id,
                        placeId=coursetable.resource,
                        order=randomSection,
                        weeknum=weekrange,
                        weekorder=randomDay,
                        sessionId=sessionId,
                        classId=coursetable.teachclass,
                        teacherId=coursetable.teacher
                    )
                    db.session.add(scheduletable)
                    scheduletables.append(scheduletable)
                    scheduletable1 = ScheduleTable(
                        courseId=coursetable.id,
                        placeId=coursetable.resource,
                        order=randomSection + 1,
                        weeknum=weekrange,
                        weekorder=randomDay,
                        sessionId=sessionId,
                        classId=coursetable.teachclass,
                        teacherId=coursetable.teacher
                    )
                    db.session.add(scheduletable1)
                    tempavg -= 1
                    timerange -= 2
        coursetable.status = 1
        db.session.commit()
        return "ok"
